package com.grad.webstudy.annota.resolver;

import com.grad.webstudy.annota.CurrentUser;
import com.grad.webstudy.constants.TokenConstants;
import com.grad.webstudy.enums.ExceptionEnums;
import com.grad.webstudy.exceptions.CustomException;
import com.grad.webstudy.exceptions.UserException;
import com.grad.webstudy.model.Token;
import com.grad.webstudy.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * @Description: 获取当前用户的注解的解析器
 * @Author: zjf
 * @Date: 2020/1/19 15:46.
 */
public class CurrentUserArgumentResolver implements HandlerMethodArgumentResolver {


    @Autowired
    private TokenService tokenService;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        boolean result = methodParameter.hasParameterAnnotation(CurrentUser.class);
        return result;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {

        //获取用户方式，一个是从缓存中，一个是从request中,这里采用从缓存中获取

        String token = nativeWebRequest.getHeader(TokenConstants.TOKEN);

        //token校验失败，抛出自定义异常
        if (!tokenService.checkToken(token)) {
            throw new CustomException(ExceptionEnums.TOKEN_INVALID.getCode(),
                    ExceptionEnums.TOKEN_INVALID.getMessage());
        }
        Token tokenEntity = tokenService.getToken(token);
        if (tokenEntity.getUser() != null) {
            tokenService.refresh(token);
            return tokenEntity.getUser();
        }

        throw new UserException("用户不存在");
    }
}
